from turtle import numinput


class Node:                 # 链表上的节点
    def __init__(self,item):
        self.item = item
        self.next = None

    def __repr__(self):
        return str(self.item)


class linklist:             # 链表
    def __init__(self):
        self.head = None
        self.tail = None
        self.num = 0
        
        
    def Hcrweate_linklist(self,li:list): # 头插法 添加元素
        head = Node(li[0])
        head.next = self.head
        num = 1
        for element in li[1:]:
            node = Node(element)
            node.next = head
            head = node
            num += 1
        self.head = head
        self.num += num
    
    def Tcrweate_linklist(self,li:list): # 尾巴插入法 添加元素
        head = Node(li[0])
        tail = head
        num = 1
        for element in li[1:]:
            node = Node(element)
            tail.next = node
            tail = node
            num += 1
        self.tail.next = head
        self.num += num
    
    def print_linklist(self):# 循环输出节点
        li = self.head
        while li:
            print(li.item, end = " ")
            li = li.next
        print()

    def insert_Node(self,index,node):   #插入节点
        if index:                       #如果索引不为0
            li = self.head              #循环 找到需要被插入的位置
            for i in range(1,index):
                li = li.next
            node.next = li.next
            li.next = node
        else:                           # 如果索引为0
            node.next = self.head       
            self.head = node            # 插入头节点

    def delete_Node(self,index):        # 删去节点
        if index:                       # 如果被删去的节点不位于头节点
            li = self.head
            for i in range(1,index):
                li = li.next
            li.next = li.next.next
        else:                           # 如果位于头节点
            self.head = self.head.next

    def search_Index(self,index):       # 索引节点
        if index:                       # 如果索引不为0
            point = self.head
            for x in range(0,index):
                point = point.next
            return point

        return self.head                # 如果索引为0

    def search_Node(self,element):      # 索引值位置
        point = self.head
        num = 0
        while(point.item!= element ):
            point = point.next
            num += 1
        return num
        



if __name__ == "__main__":
    N1 = linklist()
    l1 = [1,2,3,4]
    print("这是一个列表:",l1)
    N1.Hcrweate_linklist(l1)
    print("已经用头插法 转化为链表")
    print("打印链表:")
    N1.print_linklist()
    print("在索引为1处添加一个值为7的节点:")
    N1.insert_Node(1,Node(7))
    N1.print_linklist()
    print("删除索引为1的节点")
    N1.delete_Node(1)
    N1.print_linklist()
    print("寻找一个值为1的节点")
    print(N1.search_Node(1))